package plus.easydo.starter.mybatis.plus.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import java.util.List;

/**
 * @author laoyu
 * @version 1.0
 */
public class MPResultUtil {

    private MPResultUtil() {
    }

    public static <T> MPDataResult buildPageData(IPage<T> page, List<T> list) {
        Integer pageNum = (int)page.getCurrent();
        Integer pageSize = (int)page.getSize();
        Integer startRow = (int)(page.getCurrent() * page.getSize());
        Integer endRow = (int)(page.getCurrent() + page.getSize());
        Long total = page.getTotal();
        Integer pages = (int)page.getPages();
        return buildPageData(pageNum, pageSize, startRow, endRow, total, pages, list);
    }


    public static <T> MPDataResult buildPageData(IPage<T> page) {
        List<T> list = page.getRecords();
        return buildPageData(page, list);
    }

    public static <T> MPDataResult buildPageData(List<T> pageList, Integer pageNum, Integer pageSize) {
        if (CollectionUtils.isEmpty(pageList)) {
            return buildPageData(pageNum, pageSize, 0, 0, 0L, 0, pageList);
        } else {
            Integer count = pageList.size();
            int pageCount;
            if (count % pageSize == 0) {
                pageCount = count / pageSize;
            } else {
                pageCount = count / pageSize + 1;
            }

            int fromIndex;
            int toIndex;
            if (!pageNum.equals(pageCount)) {
                fromIndex = (pageNum - 1) * pageSize;
                toIndex = fromIndex + pageSize;
            } else {
                fromIndex = (pageNum - 1) * pageSize;
                toIndex = count;
            }

            List<T> list = pageList.subList(fromIndex, toIndex);
            return buildPageData(pageNum, pageSize, fromIndex, toIndex, (long)count, pageCount, list);
        }
    }

    private static <T> MPDataResult buildPageData(Integer pageNum, Integer pageSize, Integer startRow, Integer endRow, Long total, Integer pages, List<T> list) {
        MPDataResult dataResult = new MPDataResult();
        dataResult.setPageNum(pageNum);
        dataResult.setPageSize(pageSize);
        dataResult.setStartRow(startRow);
        dataResult.setEndRow(endRow);
        dataResult.setTotal(total);
        dataResult.setCount(total);
        dataResult.setPages(pages);
        dataResult.setData(list);
        return dataResult;
    }

    public static <T> MPDataResult buildPage(IPage<T> page, List<T> list) {
        Integer pageNum = (int)page.getCurrent();
        Integer pageSize = (int)page.getSize();
        Integer startRow = (int)((page.getCurrent() - 1L) * page.getSize());
        Integer endRow = (int)(page.getCurrent() * page.getSize());
        Long total = page.getTotal();
        Integer pages = (int)page.getPages();
        return buildPageData(pageNum, pageSize, startRow, endRow, total, pages, list);
    }
}
